const express = require('express');
const router = express.Router();
const {Article} = require('../../models');
const {Op} = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { Success, failure } = require('../../utils/responses');

//获取所有文章列表
router.get('/', async (req, res) => {
    try {
        const query = req.query;
        //分页查询需要的参数
        const currentPage = Math.abs(query.currentPage) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [["id", "DESC"]],
            offset: offset,
            limit: pageSize
        };
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            };
        }


        const articles = await Article.findAndCountAll(condition);
        Success(res, '文章查询成功', {
            rows: articles.rows,
            pagination: {
                total: articles.count,
                currentPage: currentPage,
                pageSize: pageSize
            }
        });
    } catch (err) {
        failure(res, err);
    }
});
//获取指定文章
router.get('/:id', async (req, res) => {
    try {

        const article = await GetArticle(req);
        Success(res, '获取文章成功', article);
    } catch (err) {
        failure(res, err);
    }
});
//创建文章
router.post('/', async (req, res) => {
    try {

        //白名单过滤
        const body = FilterBody(req);
        const article = await Article.create(body);

        Success(res, '创建文章成功', article, 201);
    } catch (error) {
        console.log("错误信息：", error);

        failure(res, error);

    }
});
//更新文章
router.put('/:id', async (req, res) => {
    try {
        const article = await GetArticle(req);
        await article.update(req.body);
        Success(res, '更新成功！', article, 200)
    } catch (err) {
        failure(res, err);
    }
});

//删除文章
router.delete('/:id', async (req, res) => {
    try {
        const article = await GetArticle(req);
        await article.destroy();
        Success(res, '删除成功');

    } catch (err) {
        failure(res, err);
    }
});


//白名单过滤
function FilterBody(req) {
    return body = {
        title: req.body.title,
        content: req.body.content
    };
}

//获取article对象
async function GetArticle(req) {
    const {id} = req.params;
    console.log(id);
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID:${id}的文章未找到`);
    }
    return article;
}

module.exports = router;